#!/usr/bin/env python3
# vim: tabstop=4 shiftwidth=4 expandtab

import argparse
from pathlib import Path

from gemini_antenna.db import AntennaDB

argparser = argparse.ArgumentParser(
    description="CLI tool to manage Antenna",
    epilog="Call '%(prog)s refresh --help' to see subcommand options."
)
subparsers = argparser.add_subparsers(
    dest="command", required=True, help="sub-command help"
)

parser_refresh = subparsers.add_parser(
    "refresh", help="check feeds for new updates"
)
parser_refresh.add_argument(
    "-f", "--force", action="store_true", help="Run even if queue is empty."
)
parser_refresh.add_argument(
    "-F", "--feedpage",
    help="File to output generated RSS/Atom/gemsub feed text/gemini to. "
          "Defaults to stdout."
)
parser_refresh.add_argument(
    "-A", "--atomfeedpage",
    help="File to output generated RSS/Atom/gemsub feed Atom XML to. "
         "Defaults to stdout."
)
parser_refresh.add_argument(
    "-T", "--twtxtpage",
    help="File to output generated twtxt text/gemini to. "
         "Defaults to stdout."
)
parser_refresh.add_argument(
    "-t", "--twtxtfile",
    help="File to output generated twtxt text/plain to. Defaults to stdout."
)
parser_refresh.add_argument(
    "-S", "--statfile", default=None,
    help="File to output feed statistics to. Defaults to stdout."
)
parser_refresh.add_argument(
    "-q", "--silent", action="store_true",
    help="Do not output. This overrides '--feedpage/--atomfeedpage/--twtxtpage/"
          "--twtxtfile/--statfile'."
)

parser_list = subparsers.add_parser("list", help="list all URLs in the table")

parser_delete = subparsers.add_parser(
    "delete", help="delete all the given URLs from the table"
)
parser_delete.add_argument("URLs", nargs="+")

parser_add = subparsers.add_parser(
    "add", help="bulk addition of feeds to queue"
)
parser_add.add_argument("URLs", nargs="+")

argparser.add_argument(
    "-d", "--dataroot", type=Path, default=Path.cwd(),
    help="Set the data directory where Antenna will store its files. "
         "Defaults to the current directory."
)

def main():
    args = argparser.parse_args()

    if args.command == "refresh":
        import gemini_antenna.ingestfeeds
        gemini_antenna.ingestfeeds.actionRefresh(args)
        return

    db = AntennaDB(args.dataroot / "antenna.sqlite")
    if args.command == "list":
        print('\n'.join(db.getQueue()))
    elif args.command == "delete":
        db.deleteFromQueue(*args.URLs)
    elif args.command == "add":
        db.queueFeed(*args.URLs)

if __name__ == "__main__":
    main()
